<?php
declare (strict_types = 1);
namespace app\video\model;
use app\common\model\BaseModel;
use app\common\self\SelfRedis;
use app\mall\model\Activity;
use app\mall\model\Goods;
use app\user\model\UserVideoProfit;
use think\facade\Db;
use think\Model;

use app\user\model\User;

Class VideoComment extends BaseModel
{
    public $field = 'id,uid,content,add_time,child_count';
    public $error = '';

    // 获取列表操作
    public function getList($get)
    {
        $relation_id =  isset($get['relation_id']) ? $get['relation_id'] : 0;
        if($relation_id <= 0)
            retu_json(400,'该视频没有评论列表');
        $where = [
            ['relation_id','=',$relation_id]
        ];
        $oredr = 'add_time desc';
        $this->queryList($get,$this->field,$where,$oredr);
        // 评论
        foreach($this->modelList as $k => $i){
            $this->list['data'][$k]['user_nickname'] = '美妆说';
            $this->list['data'][$k]['user_avatarurl'] = 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/icon/%E7%BC%96%E7%BB%84%205%402x.png';
            if($i->oneUser){
                $this->list['data'][$k]['user_nickname'] = $i->oneUser->nickname;
                $this->list['data'][$k]['user_avatarurl'] = $i->oneUser->avatarurl;
            }
            $this->list['data'][$k]['content'] = emojiDecode($i['content']);//转义特殊表情
            // 下级评论数需要大于0
            if($i->child_count > 0 && $i->ManyCommentChild){
                $child_coment = $i->ManyCommentChild()->order($oredr)->find();
                $this->list['data'][$k]['child_comment'] = $child_coment->toArray();
                $this->list['data'][$k]['child_comment']['__id'] = $child_coment->id;
                if(!$child_coment)
                    continue;
                // 拿取用户头像 用户昵称
                if($child_coment->oneUser && $child_coment->poneUser){
                    $this->list['data'][$k]['child_comment']['user_nickname'] = '美妆说';
                    $this->list['data'][$k]['child_comment']['user_avatarurl'] = 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/icon/%E7%BC%96%E7%BB%84%205%402x.png';
                    // 当前评论人的用户头像和地址
                    if($child_coment->oneUser){
                        $this->list['data'][$k]['child_comment']['user_nickname'] = $child_coment->oneUser->nickname;
                        $this->list['data'][$k]['child_comment']['user_avatarurl'] = $child_coment->oneUser->avatarurl;
                    }
                    $this->list['data'][$k]['child_comment']['content'] = emojiDecode($child_coment['content']);

                    $this->list['data'][$k]['child_comment']['p_user_nickname'] = '美妆说';
                    $this->list['data'][$k]['child_comment']['p_user_avatarurl'] = 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/icon/%E7%BC%96%E7%BB%84%205%402x.png';
                    // @ 人的用户和头像信息
                    if($child_coment->poneUser){
                        $this->list['data'][$k]['child_comment']['p_user_nickname'] = $child_coment->poneUser->nickname;
                        $this->list['data'][$k]['child_comment']['p_user_avatarurl'] = $child_coment->poneUser->avatarurl;
                    }
                }
            }
        }
    }

    /**
     * @param $id 查询当前id，并进行判断数据范湖
     * @return array|null|Model|void 返回当前记录
     */
    public function getOne($id){
        if(!$id || $id <= 0)
            return retu_json(400,'列表记录为空');
        // ->field('id,name,title,cover,share,default_price,default_discount_price')
        //$field = 'id,uid,type,relation_id,title,cover,video,likes,shares,comments,add_time';
        $oneModel = $this->where(['is_check'=>0,'is_delete'=>0])->field($this->field)->find($id);
        if(!$oneModel)
            return retu_json(400,'没有该记录');

        // 判断类型是否正确 1表示商品  2 表示活动
        //类型为1 如果是商品id
        if($oneModel['type'] == 1){
            if(!$oneModel->getModelGoods)
                return retu_json(400,'此商品不存在');
            // 拿取到商品信息
            $oneModel['goods'] = $oneModel->getFieldData([$oneModel->getModelGoods->toArray()],'id,title,name,cover,share,default_price,default_discount_price');
            unset($oneModel->getModelGoods);
        }else{
            if(!$oneModel->getModelActivity)
                return retu_json(400,'此活动不存在');
            if($oneModel->getModelActivity->status != 0)
                return retu_json(400,'活动已下架');
            if($oneModel->getModelActivity->hours <= time())
                return retu_json(400,'活动已过期');
            $oneModel['activity'] = $oneModel->getFieldData([$oneModel->getModelActivity->toArray()],'id,name,cover,hours,title,share,num,content');
            unset($oneModel->getModelActivity);
        }
        return $oneModel;
    }


    /**
     * 一对一关联
     */
    public function oneUser()
    {
//        $list = $this->find(1);
//        dump($list->user->nickname);
//        exit;
        // 父user  id  ，  当前字段的id
        return $this->hasOne(User::class,'id','uid');
    }

    /**
     * 一对多关联 获取到下级评论
     */
    public function ManyCommentChild()
    {
        // 关联商品表goods  商品表goods的id  ，  当前关联字段名称
        return $this->hasMany(VideoCommentChild::class,'fid','id');
    }

    /**
     * 一对一关联 此处获取到活动id
     */
    public function getModelActivity()
    {
        // 关联活动表  活动表的id  ，  当前关联字段名称
        return $this->hasOne(Activity::class,'id','relation_id');
    }

    /*
     一对多关联
     $list->comments // 查询单条记录
    // 按照条件查询
    dump($list->comments()->where('id',1)->select()->toArray());
    //  一对多关联
    public function comments()
    {
        return $this->hasMany(User::class,'id','uid');
    }
    */


    /*
     * 获取我的评论是否有新数据
     */
    public function getNewComment($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $where[] = ['uid','=',$id];
            $where[] = ['type','=',2];
            $where[] = ['is_delete','=',0];
            $redis = new SelfRedis();
            $time = $redis->redis->get('video:comment_time:'.$id);
            if(!$time) $time = 0;
            $where[] = ['add_time','>',$time];
            $list = $this->field('count(id) as is_comment')
                ->union("SELECT count(id) as is_comment FROM m3_video_comment_child where uid={$id} and add_time>{$time} and is_delete=0")
                ->union("SELECT count(id) as is_comment FROM m3_video_comment_child where upid={$id} and add_time>{$time} and is_delete=0")
                ->where($where)
                ->select();
            $count = 0;
            if(!empty($list))
                foreach($list as $k=>$v){
                    if($v['is_comment']>0){
                        $count = $v['is_comment'];
                        break;
                    }
                }
            return $count>0?true:false;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 获取我的评论列表
     */
    public function getCommentList($id){
        try{
            if(empty($id)) exception('找不到该用户!');
            $data = Input('post.');
            $redis = new SelfRedis();
            $redis->redis->set('video:comment_time:'.$id,time());
            $where = ['v.uid'=>$id,'v.is_check'=>1,'v.status'=>1,'c.type'=>2,'v.is_delete'=>0,'c.is_delete'=>0];
            $where1 = ['vc.upid'=>$id,'v.is_check'=>1,'v.status'=>1,'c.type'=>2,'v.is_delete'=>0,'vc.is_delete'=>0];
            $field = 'v.id as vid,u.id,v.cover,v.video,u.nickname,u.avatarurl,c.content,c.add_time';
            $field1 = 'v.id as vid,u.id,v.cover,v.video,u.nickname,u.avatarurl,vc.content,vc.add_time';
            $limit = isset($data['limit'])&&!empty($data['limit']) ? $data['limit'] : 15;//每页显示数据
            $query = ['page' => (isset($data['page']) ? $data['page'] : 1)];//分页参数
            $comment = $this->alias('c')->join('video v','v.id=c.relation_id','left')->join('user u','u.id=c.uid','left')->field($field)->where($where)->buildSql();
            $comment_child = Db::name('video_comment_child')->alias('vc')->join('video_comment c','c.id=vc.fid','left')->join('video v','v.id=c.relation_id','left')
                ->join('user u','u.id=vc.uid','left')->field($field1)->where($where1)->unionAll([$comment])->buildSql();
            $item = Db::table($comment_child)->alias('union')->order('add_time desc')->paginate($limit, false, array('query'=>$query));
            $list = empty($item) ? array():$item->toArray();
            if(!empty($list['data'])){
                $year = date('Y',time());
                foreach($list['data'] as $k=>$v){
                    $list['data'][$k]['content'] = emojiDecode($v['content']);
                    if($year == date('Y',$v['add_time'])) $list['data'][$k]['add_time'] = date('m-d',$v['add_time']);
                    else $list['data'][$k]['add_time'] = date('Y-m-d',$v['add_time']);
                }
            }
            return $list;
        }catch (\Exception $e){
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }

    /*
     * 添加一级评论 视频
     */
    public function addComment($user){
        try{
            if(empty($user->id)) exception('找不到该用户!');
            $data = Input('post.');
            if(empty($data['id']))
                exception('请选择评论的视频');
            if(empty($data['content']))
                exception('请输入回复内容');

            $ins = [
                'type'=>2,
                'uid'=>$user->id,
                'relation_id'=>$data['id'],
                'content'=>(emojiEncode($data['content'])),//转义表情
                'add_time'=>time()
            ];
            $this::startTrans();
            $vid = $this->insertGetId($ins);
            $fid = (new Video())->where(['id'=>$data['id']])->inc('comments',1)->update(); #child_count字段自增
            if($user->level > 1) $pid = (new UserVideoProfit())->updateProfit(['uid'=>$user->id,'type'=>4]);#视频任务记录
            $this::commit();
            return ['fid'=>$vid,'uid'=>$user->id,'add_time'=>$ins['add_time']];
        }catch (\Exception $e){
            $this::rollback();
            if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else $this->error = $e->getMessage();
            return false;
        }
    }
}